package com.stage.service;


import com.stage.util.ObjectManager;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import javax.persistence.Column;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Stage on 2017/4/14.
 */
public class ObjectCrudService {
    //工厂
    private static final SessionFactory ourSessionFactory;
    private static ArrayList<String> objects = new ArrayList<>();

    //初始化工厂
    static {
        try {
            Configuration configuration = new Configuration();
            configuration.configure();

            ourSessionFactory = configuration.buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    //获取session
    public static Session getSession() throws HibernateException {
        return ourSessionFactory.openSession();
    }

    public void readNode(Element root, String prefix) {
        if (root == null) return;
        // 获取属性
        List<Attribute> attrs = root.attributes();
        if (attrs != null && attrs.size() > 0) {
            for (Attribute attr : attrs) {
                objects.add(attr.getValue() + " ");
            }
        }
        // 获取他的子节点
        List<Element> childNodes = root.elements();
        prefix += "\t";
        for (Element e : childNodes) {
            readNode(e, prefix);
        }
    }

    public ArrayList<String> getAllObejctName() {
        try {
            objects.clear();
            SAXReader reader = new SAXReader();
            File f = new File("D:\\后端学习测试\\ObjectCRUD\\src\\com\\stage\\service\\Objects.xml");
            InputStream in = new FileInputStream(f);
            Document doc = reader.read(in);
            Element root = doc.getRootElement();
            readNode(root, "");
            return objects;
        } catch (DocumentException e) {
            e.printStackTrace();
            return objects;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return objects;
        }
    }

    public Map<String, String> getObjectColumns(String objectName) {
        try {
            return getColumns(Class.forName("com.stage.models." + objectName + "Entity"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    private Map<String, String> getColumns(Class classtype) {
        Method[] methods = classtype.getMethods();
        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < methods.length; i++) {
            Annotation[] annotations = methods[i].getAnnotations();
            for (int j = 0; j < annotations.length; j++) {
                if (annotations[j] instanceof Column) {
                    Column column = (Column) annotations[j];
                    if (!column.name().equals("Id"))
                        map.put(column.name(), toLowerCaseFirstOne(column.name()));
                }
            }
        }
        return map;
    }

    private String toLowerCaseFirstOne(String s) {
        if (Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }

    public ArrayList<Object> getObjectData(String objectName) {
        Class object = null;
        try {
            object = Class.forName("com.stage.models." + objectName + "Entity");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        ArrayList<Object> result;
        Session session = getSession();
        Query que = session.createNativeQuery("select * from " + objectName, object);
        result = (ArrayList<Object>) que.list();
        return result;

    }

    public boolean deleteObjectData(String objectName, Integer id) {
        boolean result;
        Session session = getSession();
        try {
            Transaction tx = session.beginTransaction();
            Query sqlQuery = session.createNativeQuery("delete from " + objectName + " where id =" + id);
            sqlQuery.executeUpdate();
            result = true;
            tx.commit();
        } catch (Exception e) {
            result = false;
            e.printStackTrace();
        }
        return result;
    }

    public ArrayList<Object> AddObjectData(String objectName) {
        Session session = getSession();
        Transaction tx = session.beginTransaction();
        session.save(ObjectManager.createObjectWithRequest(objectName));
        tx.commit();
        return getObjectData(objectName);
    }

    public ArrayList<Object> updateObjectData(String objectName) {
        Session session = getSession();
        Transaction tx = session.beginTransaction();
        session.update(ObjectManager.createObjectWithRequest(objectName));
        tx.commit();
        return getObjectData(objectName);
    }
}
